<?php

namespace App\Http\Controllers\Api;

use App\Models\UsersChatRecords;
use App\Repositories\Cache\LastMsgCache;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UsersChatList;
use App\Repositories\WebSocket\ClientManager;
use App\Repositories\WebSocket\UnreadTalk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TalkController extends Controller
{
    /**
     * 未读消息类
     * 
     * @var UnreadTalk 
     */
    private $unreadTalk;

    /**
     * 客户端Fd管理
     * 
     * @var ClientManager 
     */
    private $clientManager;
    
    public function __construct()
    {
        $this->unreadTalk = new UnreadTalk();
        $this->clientManager = new ClientManager();
    }
    
    public function create(Request $request)
    {
        $receiveId = $request->input('receive_id');
        $userId = Auth::id();

        $result = UsersChatList::updateOrCreate(
            ['user_id' => $userId, 'friend_id' => $receiveId],
            ['status' => 1]
        );
        if (! $result) {
            return error("创建失败");
        }

        $data = [
            'id' => $result['id'],
            'friend_id' => $receiveId,
            'msg_text' => '',
            'online' => 1,
            'name' => '',
            'avatar' => '',
            'unread_num' => 0,
            'updated_at' => date('Y-m-d H:i:s')
        ];

        $data['unread_num'] = $this->unreadTalk->get($userId, $receiveId);

        $userInfo = User::where('id', $userId)->first(['name']);
        $data['name'] = $userInfo->nickname;
        $data['avatar'] = "";


        $records = LastMsgCache::get($receiveId, $userId);
        if ($records) {
            $data['msg_text'] = $records['text'];
            $data['updated_at'] = $records['created_at'];
        }

        return success($data);
    }

    public function grid(Request $request)
    {
        // 读取用户的未读消息列表
        $result = $this->unreadTalk->getAll(Auth::id());
        if ($result) {
            foreach ($result as $friend_id => $num) {
                UsersChatList::updateOrCreate([
                    'user_id' => Auth::id(),
                    'friend_id' => intval($friend_id),
                ], [
                    'status' => 1,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }
        }

        $filed = [
            'list.id', 'list.friend_id', 'list.updated_at','users.name',
        ];

        $rows = UsersChatList::from('users_chat_list as list')
            ->leftJoin('users', 'users.id', '=', 'list.friend_id')
            ->where('list.user_id', Auth::id())
            ->where('list.status', 1)
            ->orderBy('updated_at', 'desc')
            ->get($filed)
            ->toArray();

        if (!$rows) {
            return [];
        }
        $userId = Auth::id();
        $rows = array_map(function ($item) use ($userId) {
            $data['id'] = $item['id'];
            $data['friend_id'] = $item['friend_id'];
            $data['name'] = '';//对方昵称/群名称
            $data['unread_num'] = 0;//未读消息数量
            $data['avatar'] = '';//默认头像
            $data['remark_name'] = '';//好友备注
            $data['msg_text'] = '......';
            $data['updated_at'] = $item['updated_at'];
            $data['online'] = 0;


            $data['name'] = $item['name'];
            $data['avatar'] = "";
            $data['unread_num'] = $this->unreadTalk->get($userId, $item['friend_id']);
            $data['online'] = $this->clientManager->isOnline($item['friend_id']);

            $records = LastMsgCache::get($item['friend_id'], $userId);

            if ($records) {
                $data['msg_text'] = $records['text'];
                $data['updated_at'] = $records['created_at'];
            }

            return $data;
        }, $rows);

        // 获取聊天列表
        if ($rows) {
            array_multisort(array_column($rows, "updated_at"), SORT_DESC, $rows);
        }

        return success($rows);
    }

    public function records(Request $request)
    {
        $receiveId = $request->get('receive_id');
        $recordId = $request->get('record_id');
        $userId = Auth::id();
        $limit = 30;
        $fields = [
            'users_chat_records.id',
            'users_chat_records.user_id',
            'users_chat_records.receive_id',
            'users_chat_records.content',
            'users_chat_records.created_at',
            'users.name as nickname',
        ];

        $rowsSqlObj = UsersChatRecords::select($fields);

        $rowsSqlObj->leftJoin('users', 'users.id', '=', 'users_chat_records.user_id');
        if ($recordId) {
            $rowsSqlObj->where('users_chat_records.id', '<', $receiveId);
        }

        $rowsSqlObj->where(function ($query) use ($userId, $receiveId) {
            $query->where([
                ['users_chat_records.user_id', '=', $userId],
                ['users_chat_records.receive_id', '=', $receiveId]
            ])->orWhere([
                ['users_chat_records.user_id', '=', $receiveId],
                ['users_chat_records.receive_id', '=', $userId]
            ]);
        });

        $rows = $rowsSqlObj->orderBy('users_chat_records.id', 'desc')->limit($limit)->get()->toArray();
        $data = [
            'rows' => $rows,
            'record_id' => $rows ? $rows[count($rows) - 1]['id'] : 0,
            'limit' => $limit
        ];

        return success($data);
    }

    /**
     * 更新对话列表未读数
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateUnreadNum(Request $request)
    {
        $receive = $request->get('receive', 0);
        $user_id = Auth::id();

        $this->unreadTalk->del($user_id, $receive);

        return success();
    }
}